<template>
  <div class="multi-session-chat-container">
    <!-- 顶部导航栏 -->
    <a-layout-header class="chat-header">
      <div class="header-content">
        <h1>多会话AI聊天助手</h1>
        <div class="user-info">
          <span>欢迎，{{ authStore.user?.username || '用户' }}</span>
          <a-button type="link" @click="handleLogout">退出</a-button>
        </div>
      </div>
    </a-layout-header>

    <a-layout class="multi-session-layout">
      <!-- 左侧会话管理 -->
      <a-layout-sider width="300" class="session-manager">
        <div class="session-manager-content">
          <div class="session-manager-header">
            <h3>会话管理</h3>
            <a-button type="primary" size="small" @click="createNewSession">
              <template #icon><plus-outlined /></template>
              新建会话
            </a-button>
          </div>

          <div class="session-list">
            <!-- 置顶会话 -->
            <div v-if="pinnedSessions.length > 0" class="session-section">
              <div class="section-header">
                <pushpin-filled style="color: #faad14" />
                置顶会话
              </div>
              <div class="session-items">
                <div
                  v-for="session in pinnedSessions"
                  :key="session.id"
                  class="session-item"
                  :class="{ 
                    active: activeSessions.has(session.id), 
                    pinned: session.pinned 
                  }"
                  @click="toggleSession(session.id)"
                >
                  <div class="session-item-content">
                    <div class="session-title">
                      <span class="pinned-badge">置顶</span>
                      {{ session.title || '新会话' }}
                    </div>
                    <div class="session-info">
                      <span>{{ formatTime(session.updated_at) }}</span>
                      <div v-if="isSessionLoading(session.id)" class="session-status">
                        <a-spin size="small" />
                        <span>任务进行中</span>
                      </div>
                    </div>
                  </div>
                  <div class="session-actions">
                    <a-button
                      type="text"
                      size="small"
                      @click.stop="togglePinSession(session.id, true)"
                      title="取消置顶"
                    >
                      <pushpin-filled style="color: #faad14" />
                    </a-button>
                    <a-button
                      type="text"
                      size="small"
                      @click.stop="deleteSession(session.id)"
                      title="删除会话"
                      class="delete-btn"
                    >
                      <delete-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 普通会话 -->
            <div class="session-section">
              <div class="section-header">
                <message-outlined />
                所有会话
              </div>
              <div class="session-items">
                <div
                  v-for="session in normalSessions"
                  :key="session.id"
                  class="session-item"
                  :class="{ active: activeSessions.has(session.id) }"
                  @click="toggleSession(session.id)"
                >
                  <div class="session-item-content">
                    <div class="session-title">{{ session.title || '新会话' }}</div>
                    <div class="session-info">
                      <span>{{ formatTime(session.updated_at) }}</span>
                      <div v-if="isSessionLoading(session.id)" class="session-status">
                        <a-spin size="small" />
                        <span>任务进行中</span>
                      </div>
                    </div>
                  </div>
                  <div class="session-actions">
                    <!-- 置顶按钮 -->
                    <a-button
                      type="text"
                      size="small"
                      @click.stop="togglePinSession(session.id, false)"
                      title="置顶会话"
                    >
                      <pushpin-outlined />
                    </a-button>
                    <a-button
                      type="text"
                      size="small"
                      @click.stop="deleteSession(session.id)"
                      title="删除会话"
                      class="delete-btn"
                    >
                      <delete-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="chatStore.sessions.length === 0" class="empty-sessions">
            <div class="empty-content">
              <div class="empty-icon">💬</div>
              <p>暂无会话</p>
              <p>点击上方按钮创建新会话</p>
            </div>
          </div>
        </div>
      </a-layout-sider>

      <!-- 右侧多会话窗口 -->
      <a-layout-content class="multi-session-content">
        <div class="session-windows-container">
          <!-- 动态渲染活跃会话窗口 -->
          <div
            v-for="sessionId in Array.from(activeSessions)"
            :key="sessionId"
            class="session-window"
            :class="{ maximized: maximizedSession === sessionId }"
          >
            <!-- 窗口头部 -->
            <div class="session-window-header">
              <div class="window-title">
                <span>{{ getSessionTitle(sessionId) }}</span>
                <div v-if="isSessionLoading(sessionId)" class="window-status">
                  <a-spin size="small" />
                  <span>{{ getAiStatus(sessionId) }}</span>
                </div>
              </div>
              <div class="window-actions">
                <a-button
                  type="text"
                  size="small"
                  @click="toggleMaximize(sessionId)"
                  :title="maximizedSession === sessionId ? '最小化' : '最大化'"
                >
                  <template v-if="maximizedSession === sessionId">
                    <compress-outlined />
                  </template>
                  <template v-else>
                    <expand-outlined />
                  </template>
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  @click="closeSession(sessionId)"
                  title="关闭窗口"
                >
                  <close-outlined />
                </a-button>
              </div>
            </div>

            <!-- 窗口内容 -->
            <div class="session-window-content">
              <!-- 消息列表 -->
              <div class="messages-container" ref="messagesContainer">
                <div class="messages-list">
                  <!-- 消息项 -->
                  <div
                    v-for="message in getSessionMessages(sessionId)"
                    :key="message.id"
                    class="message"
                    :class="{ 'user-message': message.is_user }"
                  >
                    <!-- AI消息在左侧 -->
                    <div v-if="!message.is_user" class="message-left">
                      <div class="message-avatar">
                        <span class="ai-avatar">🤖</span>
                      </div>
                      <div class="message-content">
                        <!-- AI回复只显示文本消息 -->
                        <div v-if="message.content && message.content.trim()" class="message-text">
                          <span v-if="message.is_streaming && !message.is_final" class="streaming-text">
                            {{ message.content }}
                            <span class="streaming-cursor">|</span>
                          </span>
                          <!-- 流式消息状态指示器 -->
                          <div v-if="message.is_streaming && !message.is_final" class="streaming-status">
                          <span class="streaming-dot"></span>
                          <span class="streaming-text">正在输出</span>
                        </div>
                          <div v-else v-html="renderMessageContent(message.content)" class="message-content-html"></div>
                        </div>
                        
                        <div class="message-footer">
                          {{ formatTime(message.created_at) }}
                        </div>
                      </div>
                    </div>
                    
                    <!-- 用户消息在右侧 -->
                    <div v-else class="message-right">
                      <div class="message-content">
                        <!-- 图片消息 -->
                        <div v-if="message.message_type === 'image' && message.file_path" class="message-image">
                          <img 
                            :src="getImageUrl(message.file_path)" 
                            :alt="message.file_path" 
                            @click="openImagePreview(getImageUrl(message.file_path))"
                            class="clickable-image"
                          />
                        </div>
                        
                        <!-- 文件消息 -->
                        <div v-else-if="message.message_type === 'file'" class="message-file">
                          <span>📄</span>
                          <span class="file-name">{{ getFileName(message.file_path) }}</span>
                          <a-button type="link" size="small" @click="downloadFile(message.file_path)">
                            下载
                          </a-button>
                        </div>
                        
                        <!-- 文本消息 -->
                        <div v-if="message.content && message.content.trim()" class="message-text">
                          <span v-if="message.is_streaming && !message.is_final" class="streaming-text">
                            {{ message.content }}
                            <span class="streaming-cursor">|</span>
                          </span>
                          <div v-else v-html="renderMessageContent(message.content)" class="message-content-html"></div>
                        </div>
                        
                        <div class="message-footer">
                          {{ formatTime(message.created_at) }}
                        </div>
                      </div>
                      <div class="message-avatar">
                        <span class="wechat-avatar">👤</span>
                      </div>
                    </div>
                  </div>

                  <!-- 加载状态 -->
                  <div v-if="isSessionLoading(sessionId)" class="loading-message">
                    <a-spin size="small" />
                    <span>AI正在思考中...</span>
                  </div>
                </div>
              </div>

              <!-- 输入区域 - TRAE风格 -->
              <div class="input-area trae-style">
                <!-- 文件预览区域 -->
                <div v-if="getSessionFiles(sessionId).length > 0" class="file-preview-area">
                  <div v-for="file in getSessionFiles(sessionId)" :key="file.id" class="file-preview-item">
                    <div v-if="file.type === 'image' && file.filePath" class="image-preview">
                      <div class="preview-container" @click="openImagePreview(getImageUrl(file.filePath))">
                        <img :src="file.previewUrl" :alt="file.name" class="preview-image" />
                        <div class="preview-overlay">
                          <span class="preview-text">点击预览</span>
                        </div>
                      </div>
                      <div class="file-info">
                        <span class="file-name">{{ getFileName(file.filePath) }}</span>
                        <a-button type="text" size="small" @click="removeFile(file.id, sessionId)" class="remove-btn">
                          ×
                        </a-button>
                      </div>
                    </div>
                    <div v-else-if="file.filePath" class="file-preview">
                      <div class="preview-container" @click="downloadFile(file.filePath, file.fileId)">
                        <span class="file-icon">📄</span>
                        <div class="preview-overlay">
                          <span class="preview-text">点击下载</span>
                        </div>
                      </div>
                      <div class="file-info">
                        <span class="file-name">{{ getFileName(file.filePath) }}</span>
                        <div class="file-actions">
                          <a-button type="text" size="small" @click="downloadFile(file.filePath, file.fileId)" class="download-btn">
                            下载
                          </a-button>
                          <a-button type="text" size="small" @click="removeFile(file.id, sessionId)" class="remove-btn">
                            ×
                          </a-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 输入框和操作按钮整合布局 -->
                <div class="input-container">
                  <a-textarea
                    :value="getSessionInput(sessionId)"
                    @input="(e) => setSessionInput(sessionId, e.target.value)"
                    placeholder="输入消息..."
                    :rows="2"
                    @press-enter="(e) => handleEnterKey(e, sessionId)"
                    class="message-input"
                  />
                  
                  <!-- 右下角操作按钮 -->
                  <div class="action-buttons">
                    <!-- 搜索开关按钮 -->
                    <a-tooltip :title="getSessionFiles(sessionId).length > 0 ? '上传文件时联网搜索不可用' : (getSessionEnableSearch(sessionId) ? '关闭联网搜索' : '开启联网搜索')">
                      <a-button
                        type="text"
                        size="small"
                        :class="['search-btn', { active: getSessionEnableSearch(sessionId), disabled: getSessionFiles(sessionId).length > 0 }]"
                        @click="getSessionFiles(sessionId).length > 0 ? null : toggleSearch(sessionId)"
                        :disabled="getSessionFiles(sessionId).length > 0"
                      >
                        <template #icon>
                          <global-outlined :class="['search-icon', { active: getSessionEnableSearch(sessionId), disabled: getSessionFiles(sessionId).length > 0 }]" />
                        </template>
                      </a-button>
                    </a-tooltip>
                    
                    <!-- 上传文件按钮（附件图标） -->
                    <a-dropdown :trigger="['click']" placement="topRight">
                      <a-button type="text" size="small" class="upload-btn">
                        <template #icon><paper-clip-outlined /></template>
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item @click="() => triggerFileUpload('image', sessionId)">
                            <picture-outlined /> 上传图片
                          </a-menu-item>
                          <a-menu-item @click="() => triggerFileUpload('file', sessionId)">
                            <file-outlined /> 上传文件
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                    
                    <!-- 发送按钮（火箭图标） -->
                    <a-button
                      type="primary"
                      size="small"
                      @click="() => handleSendMessage(sessionId)"
                      :loading="isSessionLoading(sessionId)"
                      :disabled="!getSessionInput(sessionId)?.trim() && getSessionFiles(sessionId).length === 0"
                      class="send-btn"
                    >
                      <template #icon><rocket-outlined /></template>
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="activeSessions.size === 0" class="no-active-sessions">
            <div class="welcome-message">
              <h2>欢迎使用多会话AI聊天助手</h2>
              <p>请从左侧选择一个或多个会话来开始聊天</p>
              <p>支持同时打开多个会话窗口，每个会话独立进行AI回复</p>
            </div>
          </div>
        </div>
      </a-layout-content>
    </a-layout>

    <!-- 图片预览模态框 -->
    <a-modal
      v-model:open="imagePreviewVisible"
      :footer="null"
      :closable="false"
      width="60vw"
      :body-style="{ padding: 0, textAlign: 'center', display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '400px' }"
      @cancel="closeImagePreview"
      class="image-preview-modal"
    >
      <img 
        :src="previewImageUrl" 
        :alt="previewImageUrl" 
        style="max-width: 100%; max-height: 70vh; object-fit: contain;"
      />
      <div style="position: absolute; top: 16px; right: 16px;">
        <a-button 
          type="primary" 
          @click="closeImagePreview" 
          size="small"
          shape="circle"
          class="close-preview-btn"
        >
          <template #icon>
            <close-outlined />
          </template>
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { useChat } from './Chat.js'
import { PlusOutlined, UploadOutlined, SendOutlined, DeleteOutlined, PushpinOutlined, PushpinFilled, MessageOutlined, ExpandOutlined, CompressOutlined, CloseOutlined, PaperClipOutlined, PictureOutlined, FileOutlined, RocketOutlined, SearchOutlined, GlobalOutlined } from '@ant-design/icons-vue'

// 使用拆分出的Chat逻辑
const {
  authStore,
  chatStore,
  loading,
  messagesContainer,
  activeSessions,
  maximizedSession,
  imagePreviewVisible,
  previewImageUrl,
  pinnedSessions,
  normalSessions,
  loadSessions,
  createNewSession,
  activateSession,
  deactivateSession,
  toggleSession,
  closeSession,
  toggleMaximize,
  getSessionTitle,
  getSessionMessages,
  getSessionMessageCount,
  getSessionFiles,
  getSessionInput,
  setSessionInput,
  isSessionLoading,
  getSessionEnableSearch,
  toggleSearch,
  openImagePreview,
  closeImagePreview,
  isSessionActive,
  getAiStatus,
  beforeUpload,
  removeFile,
  triggerFileUpload,
  handleEnterKey,
  handleSendMessage,
  togglePinSession,
  deleteSession,
  getImageUrl,
  downloadFile,
  getFileName,
  formatTime,
  scrollToBottomNextTick,
  isScrolledUp,
  renderMessageContent,
  handleLogout
} = useChat()
</script>

<style scoped>
@import './Chat.css';
</style>